<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\util;

use app\common\constants\MenuConstant;
use EasyWeChat\Factory;
use think\facade\Db;

class WechatService
{


    //实例化小程序
    public function wechatXcx()
    {
        //配置微信小程序
        $config = [
            'app_id' => config('app.wechat.appid'),
            'secret' => config('app.wechat.appsecret'),
            'response_type' => 'array',
        ];
        $restult = Factory::miniProgram($config);
        return $restult;
    }




    //获取手机号
    public function getPhone($code = '')
    {
        $accessToken = $this->wechatXcx()->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token['access_token'];
        $arr['code'] = $code;
        $result = json_post($url, $arr);
        return $result;

    }

    /**
     * 微信支付下订单接口
     */
    public static function pay($orderno='',$body='',$amount='',$openid='')
    {
        $config = [
            'app_id' => config('app.wechat.appid'),
            'mch_id' => config('app.wechat.mch_id'),
            'key' =>  config('app.wechat.key'),
            'notify_url' => config('app.app_host').'/api/Wechat/notify',
            'cert_path' =>  config('app.wechat.cert_path'),
            'key_path' => config('app.wechat.key_path'), // XXX: 绝对路径！！！
        ];
        try {

         $app = Factory::payment($config);

            $jssdk = $app->jssdk;

            $result = $app->order->unify([
                'body' => $body,
                'out_trade_no' =>$orderno,
                'total_fee' =>$amount * 100,
                'spbill_create_ip' => '',
                // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => '/api/Wechat/notify',
                // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI',
                // 请对应换成你的支付方式对应的值类型
                'openid' => $openid,
            ]);

            if ($result['return_code'] != 'SUCCESS') {

                throw new \Exception("支付失败");
            }
            $json = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回 json 字符串，如果想返回数组，传第二个参数 false
            $code = 1;
            $mes='成功';
        } catch (\Exception $e) {
           $mes = $e->getMessage();
           $code = 0;
           $json = '';
        }
        return $json;
    }

   /**
     * 微信支付订单签约
     */
    public static function signingPay($orderno='',$body='',$amount='',$openid='')
    {
    
        $config = [
            'app_id' => config('app.WechatWithhold.appid'),
            'secret' => config('app.WechatWithhold.appsecret'),
            'mch_id' => config('app.WechatWithhold.mchid'),
            'sub_mch_id' => config('app.WechatWithhold.sub_mch_id'),
            'key' =>  config('app.WechatWithhold.key'),
            'notify_url' => config('app.app_host').'/api/Wechat/notify',
            'cert_path' =>  config('app.wechat.cert_path'),
            'key_path' => config('app.wechat.key_path'), // XXX: 绝对路径！！！
        ];
        try {

         $app = Factory::payment($config);
            $jssdk = $app->jssdk;
            $isContract = true;
            $result = $app->order->unify([
                'body' => $body,
                'out_trade_no' =>'QYP'.$orderno,
                'total_fee' =>$amount * 100,
                'spbill_create_ip' => '',
                // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' =>  config('app.app_host').'/api/Wechat/notify',
                // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI',
                // 请对应换成你的支付方式对应的值类型
                'openid' => $openid,
                'plan_id' => config('app.WechatWithhold.templet_id'),// 协议模板id
                'contract_code' => 'Qy'.generateOrder(),// 签约协议号
                'contract_display_account' => 'QALTIS会员费',// 签约用户的名称
                'contract_notify_url' => config('app.app_host').'/api/Wechat/notify'

            ],$isContract);
            print_r($result);
            if ($result['return_code'] != 'SUCCESS') {

                throw new \Exception("支付失败");
            }
            $json = $result;
           // $json = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回 json 字符串，如果想返回数组，传第二个参数 false
            $code = 1;
            $mes='成功';
        } catch (\Exception $e) {
           $mes = $e->getMessage();
           $code = 0;
           $json = '';
        }
        return $json;
    }



    /**
     *  微信退款
     */
    public static function refund($transactionId,$refundNumber,$refundFee,$totalFee)
    {

        // $param = $this->request->param();
        $config = [
            'app_id' => config('app.appid'),
            'secret' => config('app.appsecret'),
            'mch_id' => config('app.mch_id'),
            'key' => '66ee297d2f68b1dd96f0b5eefc7a4925',
            'notify_url' => 'https://www.zgtygy.cn/api/Wechat/notify',
            'cert_path' => 'path/to/your/cert.pem',
            // XXX: 绝对路径！！！！
            'key_path' => 'path/to/your/key', // XXX: 绝对路径！！！
        ];
            // $row = Db::table('ea_order')->where('orderno',$orderno)->where('status','0')->find();
            // if(!$row){
            //     throw new \Exception("该订单不存在");
            // }
            // $member = Db::table('ea_member')->where('id',$row['memberid'])->find();
            $app = Factory::payment($config);
            $result = $app->refund->byTransactionId($transactionId, $refundNumber, $totalFee, $refundFee, $config = []);
            return $result;

    }

    /**
     * 微信支付回调
     */
    public static function notify($result = [])
    {
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            //修改代扣订单
           if(strpos($result['out_trade_no'],'VIP') === false){ 
              $order = Db::name('order')->where('out_trade_no', $result['out_trade_no'])->find();
              Db::name('order')->where('out_trade_no', $result['out_trade_no'])->update(['status' => '1', 'pay_time' => date('Y-m-d H:i:s', time())]);
              $map['is_vip'] = 1;
              $map['vip_id'] = $order['vip_id'];
              $usage_time = $order['usage_time'];
              $map['vip_endtime'] = date('Y-m-d',strtotime("+ $usage_time day"));
              Db::name('member')->where('id',$order['memberid'])->update($map);
           }
            return true;
        }
    }
    /**
     * 发送订阅消息通知
     */
    public static function sendxcxNotice($data=[])
    {
        $config = [
            'app_id' => config('app.wechat.appid'),
            'secret' => config('app.wechat.appsecret'),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 
        $zxurl = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $token['access_token'];
        $data = json_encode($data);
        $result = json_post($zxurl, $data);
        $result = json_decode($result, true);
        print_r($result);
    }
}